let _Vue = null

export default class VueRouter {
  constructor (options) {
    this.options = options
    this.routeMap = {}
    this.data = _Vue.observable({
      current: '/'
    })
    this.init()
  }

  static install (Vue) {
    // 判断当前VueRouter插件是否已经安装
    if (VueRouter.install.installed) return
    VueRouter.install.installed = true
    // 把Vue构造函数挂载到全局变量
    _Vue = Vue
    // 把创建Vue实例时传入的router对象注入到所有Vue实例
    _Vue.mixin({
      beforeCreate () {
        if (this.$options.router) _Vue.prototype.$router = this.$options.router
      }
    })
  }

  init () {
    this.createRouteMap()
    this.initComponents(_Vue)
    this.initEvent()
  }

  // 把传入的路由规则转换为键值对存储到routeMap
  createRouteMap () {
    for (const route of this.options.routes) {
      this.routeMap[route.path] = route.component
    }
  }

  // 创建router-view和router-link组件
  initComponents (Vue) {
    Vue.component('router-link', {
      props: {
        to: String
      },
      render (h) {
        return h('a', {
          attrs: {
            href: this.to
          },
          on: {
            click: this.clickHandler
          }
        }, [this.$slots.default])
      },
      methods: {
        clickHandler (e) {
          const targetHash = '#' + this.to
          history.pushState ? history.pushState({}, '', targetHash) : window.location.hash = targetHash
          // 改变current属性，加载对应组件
          this.$router.data.current = this.to
          // 404页面处理
          if (!Object.keys(this.$router.routeMap).includes(this.to)) this.$router.data.current = '*'
          e.preventDefault()
        }
      }
    })

    Vue.component('router-view', {
      render: (h) => {
        return h(this.routeMap[this.data.current])
      }
    })
  }

  // 注册hashchange和load事件
  initEvent () {
    window.addEventListener('hashchange', () => {
      const hash = window.location.hash.substr(1)
      // 改变current属性，加载对应组件
      this.data.current = hash
      // 404页面处理
      if (!Object.keys(this.routeMap).includes(hash)) this.data.current = '*'
    })
    window.addEventListener('load', () => {
      const hash = window.location.hash.substr(1)
      this.data.current = hash
      if (!Object.keys(this.routeMap).includes(hash)) this.data.current = '*'
    })
  }
}
